import json
import os

from config.sys_path import HAR_DIR


def analyse_har(filepath):
    file = open(filepath, "r", encoding='utf-8')
    har_context = file.read()
    har = json.loads(har_context)
    har_body = har["log"]["entries"]
    analyse_list = []
    for res in har_body:  # type: dict
        if res.get("timings") and res.get("time") > 1500:  # 筛选出响应时间超过1.5秒的接口
            if str(res["request"]["method"]).lower() in "get head options trace delete":
                one_list = []
                if "?" in res["request"]["url"]:
                    url_list = res["request"]["url"].split("?")
                    one_list.append(url_list[0])
                    one_list.append(url_list[1])
                else:
                    one_list.append(res["request"]["url"])
                    one_list.append("")
                one_list.append(res["time"])
            else:
                one_list = []
                one_list.append(res["request"]["url"])
                one_list.append(res["request"]["postData"])
                one_list.append(res["time"])

            analyse_list.append(one_list)
    return analyse_list


def analyse_har_folder(folder):
    har_file_list = []
    analyse_big_list = []
    for filewalks in os.walk(folder):
        for files in filewalks[2]:
            print('true files：', files)
            if ".har" in files:
                print(".har", ' is in', os.path.join(filewalks[0], files))
                har_file_list.append(os.path.join(filewalks[0], files))
    print(har_file_list)
    for har in har_file_list:
        analyse_list = analyse_har(har)
        analyse_big_list.extend(analyse_list)
    return analyse_big_list


if __name__ == '__main__':
    analyse_fin_list = analyse_har_folder(HAR_DIR)
    print(analyse_fin_list)
    for one in analyse_fin_list:
        print(one)
